package com.cjstudio.soundexample;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class PlayBeatActivity extends Activity implements OnClickListener, OnTouchListener {
	
	LinearLayout root;
	Button btnPlay;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		Log.d("NRT", "onCreated: ");
		
		
		root = (LinearLayout)findViewById(R.id.LinearLayout01);
		root.setOnTouchListener(this);
		
		btnPlay = (Button)findViewById(R.id.btnPlay);
		btnPlay.setOnClickListener(this);
    }
    
    
    @Override
	public void onResume() {
		Log.d("NRT", "onResume: ");

    		super.onResume();
    		
        initSound();
            
    		_ShakeDetectionService = new ShakeDetectionService(this);
    		_ShakeDetectionService.startShakeDetection();
    }
    
    @Override
	public void onPause() {
    		_ShakeDetectionService.stopShakeDetection();
    		super.onPause();
    }

    
    ShakeDetectionService _ShakeDetectionService;

    class ShakeDetectionService extends MyShakeDetectionService {
		public ShakeDetectionService(Context mContext) {
			super(mContext);
		}
		@Override
		public void onShakeDetected() {
			Log.d("NRT", "Shake Detected!");
			playBeat();
		}
    }
    
    public void playBeat() {
    		Log.d("NRT", "PLay Beat!");
    		playSound();
    }
    
    private SoundPool sound_pool; 
    private int sound_beep;
    private int sound_drum;
    
    private void initSound() { 
	     sound_pool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
	     sound_beep = sound_pool.load(this, R.raw.bassdrum1, 1);
	     sound_drum = sound_pool.load(this, R.raw.drum1, 1);
    } 
      
    int a = 1;
    public void playSound() { 
    		Log.d("NRT", "PLay Sound!");
    		
    		a++;
//    		if(a%2 ==0)
    			sound_pool.play(sound_beep, 1f, 1f, 0, 0, 1f);
//    		else
//    			sound_pool.play(sound_drum, 1f, 1f, 0, 0, 1f);
    }


	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch(arg0.getId()) {
		case R.id.btnPlay: 
			playSound();
		}
		
	}


	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		playSound();
		// TODO Auto-generated method stub
		return false;
	}
}